<!-- @author benjamin_5 @date 2022/10/12-->

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jQuery3.6.1.js"></script>
    <script src="js/aes.js"></script>
    <script src="js/pad-zeropadding.js"></script>
    <script src="js/jsencrypt.min.js"></script>
</head>
<body>
<div class="modal-body form ">
    <label>输入参数：<input style="width: 497px" id="param"/></label>
    <br/>
    <br/>
    <label>参数加密：<textarea rows="3" cols="60" id="aes_param"></textarea></label>
    <br/>
    <br/>
    <label>密钥加密：<textarea rows="10" cols="60" id="rsa_param"></textarea></label>
    <br/>
    <br/>
    <label>后端解密：<textarea rows="10" cols="60" id="rsa_decrypt"></textarea></label>
    <br/>
    <br/>
    <button onclick="encrypt()">加密参数</button>
    <br/>
    <br/>

</div>

</body>
<script>
    // 加密公钥
    const publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZ1NFj4UnkugYSqjPWFsxRp0JMNY//I1M1mf7zYcYLu6G3IIX/GUthNoeAd9x20MbjhOMVOf0syTnRWU1OM+jLc3YN9xWvgW3lRlhm88PCkXitZs6qJXCM3EFQakw+gjuCWafHEfNJ3gkDUovhXkJxRbqb4EB2kcUh+tinfAGlwQIDAQAB";
    // 签名私钥
    const privateSignKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKpKgupEORx1mn5RPdNeSUlfNLOU/C9E/0IjHbzk4rKg4kvK7Y8ONxKubUor89vWdBGFkeGdBqoMns2072d747kMBfyEubRKGO6OR/8lrKmlZ9gI2AOod5VwNI2A6Wy7BemzRd2ayQSe7A4UhYrOSkurv0bQY363RX1NHbQ7Fq8tAgMBAAECgYAk9acUUVpT4vJ1GAzjI0OkuRUnJN7XI5KDODvsE4FgY6q56IFG2z74vwLZZlC3FgR7CRJwdTRNFBAjdXHAdBMoa+CPFNiACih7ibipM4QEFiPG85YdYEBOdvINWZNqyjvdG8n/oNT9WSx3bUzmSAdOsCutUXd+3UwXXFvv40JnwQJBANKwdQuBw/u+T8QgqtXUyT4dGj7n80um/npKUXPxJCshvldQ94vRO25+RD2DdjrmwGo/SgMUoepE9YwL8QTZ1xMCQQDO6evgLFULrlC2NWMRHgDCuRV8PYJIH4PTD+FrsjrINmUaLEUt/CNa3vKOE0szQJRWC/uzl7YgmjgfwAxegui/AkAErKGMJc7hUPGYGllv8Q6d8Cta5e6B6SyQLgHsnpb81fzRFxzG31eANhDxhG8lE2WFde4Ab37AIdOIzeMFBog9AkAqF4QYcmxKmAdrSakBjmzxL92jDJA4Q9D5Wr2svvEeUZJ3pJHeLPC0R65oIJynrHeAmad2fWJbd4P7UYIyp8bZAkB0KiXIXa8morjqQ5ZnqKlQ9aLWYxg7ToZKHp+Bd+1c4npLb+N5L3WOhzkIO2/EPwXE9pu2VWA6ULhetZ3wNMsv";

    function encrypt() {
        var param = $("#param").val();

        // 生成密钥
        var keyStr = generateRandomKey();
        // 加密参数
        var encryptParam = aesEncrypt(param, keyStr);
        $("#aes_param").val(encryptParam);
        // 加密密钥
        var encryptKey = rsaEncrypt(keyStr, publicKey);//加密后的密码

        $("#rsa_param").val(encryptKey);

        var data = {
            "userName": encryptParam
        };
        // 发起请求
        $.ajax({
            url: "/user/add",
            type: "POST",
            headers: {
                encryptKey: encryptKey
            },
            data: data,
            processData: true,
            contentType: "application/x-www-form-urlencoded", // 告诉jQuery不要去设置Content-Type请求头
            success: function (res) {
                console.log(res);
                $("#rsa_decrypt").val(JSON.stringify(res));
            },
            error: function (res) {
                console.error("系统错误", res)
            }
        });
    }

    /**
     * 参数加密
     * @param data
     * @param keyStr
     * @returns {string}
     */
    function aesEncrypt(data, keyStr) {
        var key = CryptoJS.enc.Latin1.parse(keyStr);
        var encrypted = CryptoJS.AES.encrypt(data, key, {
            iv: key,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.ZeroPadding
        });
        return encrypted.toString();
    }

    /**
     * 密钥加密
     * @param data
     * @param publicKey
     * @returns {*}
     */
    function rsaEncrypt(data, publicKey) {
        var rsa = new JSEncrypt();
        rsa.setPublicKey(publicKey);
        return rsa.encrypt(data);
    }

    function rsaSign(data, privateKey){
        var rsa = new JSEncrypt();
        rsa.setPrivateKey(privateKey);
        var queryString = "";
        $.each(data, function(key, value) {
            var keys = Object.keys(data).sort();
            queryString += keys.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(data[k])}`).join('&');
        });
        console.log("排序", queryString);
        var sign = rsa.sign(queryString, CryptoJS.SHA256, "sha256");
        return sign;
    }

    /**
     * 生成随机密钥
     * @returns {string}
     */
    function generateRandomKey() {
        var length = 16;
        var result = '';
        var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var charactersLength = characters.length;
        for (var i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
</script>
</html>